package com.dy.lock.screen.utils;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.server.StartMain;

@Service("IDGenerater")
public class IDGenerater {
	@Value("${order.ip}")
	private String orderIp;
	@Value("${order.port}")
	private String orderPort;

	private static Logger log = Logger.getLogger(IDGenerater.class);
	private static IDGenerater idGene;

	private IDGenerater() {
	}

	public static IDGenerater getInstance() {
		if (idGene == null) {
			idGene = (IDGenerater) StartMain.APPLICATION_CONTEXT
					.getBean("IDGenerater");
		}
		return idGene;
	}

	public String getOrderNo(String... classNames) {
		String name = "IDGenerater";
		if (classNames != null && classNames.length > 0) {
			name = classNames[0];
		}

		String orderId = null;
		for (int s = 0; s < 10; s++) {
			if (orderId == null) {
				try {
					int port = 3838;
					try {
						port = Integer.parseInt(orderPort);
					} catch (Exception e) {
						log.error("", e);
						throw new ServerDisponseException(
								TransmissionCode.OBTAIN_ORDER_FAILURE.getCode(),
								TransmissionCode.OBTAIN_ORDER_FAILURE
										.getMessage());
					}
					orderId = sendMessage(orderIp, port, name);
					if (orderId == null)
						Thread.sleep(200);
				} catch (Exception e) {
					log.error("", e);
					throw new ServerDisponseException(
							TransmissionCode.OBTAIN_ORDER_FAILURE.getCode(),
							TransmissionCode.OBTAIN_ORDER_FAILURE.getMessage());
				}
			} else
				break;
		}

		return orderId;
	}

	public static String sendMessage(String ip, int port, String message) {
		Socket sc = null;
		try {
			// 打开Socket通道
			sc = new Socket();
			sc.connect(new InetSocketAddress(ip, port), 2000);
			sc.setSoTimeout(4000);
			sc.setKeepAlive(true);
			String charset = "UTF-8";
			if (message != null && message.trim().length() > 0) {
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(sc.getOutputStream(), charset));
				writer.write(message.trim());
				writer.newLine();
				writer.flush();
			}
			Scanner scan = new Scanner(sc.getInputStream(), charset);
			String st = null;
			if (scan.hasNextLine()) {
				st = scan.nextLine();
			}
			sc.getOutputStream().close();
			scan.close();
			sc.close();
			return st;
		} catch (Exception e) {
			if (sc != null && !sc.isClosed())
				try {
					sc.close();
				} catch (Exception e1) {
				}
			sc = null;
		}
		return null;
	}
}
